<!-- setup 无法设置组件名称，组件名称keepAlive必须 -->
<script lang="ts">
export default {
  name: 'client',
};
</script>

<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item>
        <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="danger" :icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-form-item>

      <el-form-item>
        <el-input v-model="queryParams.name" placeholder="客户端名称" clearable style="width: 240px" @keyup.enter="handleQuery"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="clientList"
      @selection-change="handleSelectionChange"
      border
      style="width: 100%"
    >
      <el-table-column type="selection" align="center" min-width="5%" />
      <el-table-column label="客户端名称" prop="name" align="center" min-width="20%" />
      <el-table-column label="全局开关" align="center" min-width="10%">
        <template #default="scope">
          <el-tag v-if="scope.row.isAutoMode" type="success">开启</el-tag>
          <el-tag v-else type="info">关闭</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="授权码模式" align="center" min-width="10%">
        <template #default="scope">
          <el-tag v-if="scope.row.isCode || scope.row.isAutoMode" type="success">开启</el-tag>
          <el-tag v-else type="info">关闭</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="隐藏式模式" align="center" min-width="10%">
        <template #default="scope">
          <el-tag v-if="scope.row.isImplicit || scope.row.isAutoMode" type="success">开启</el-tag>
          <el-tag v-else type="info">关闭</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="密码式模式" align="center" min-width="10%">
        <template #default="scope">
          <el-tag v-if="scope.row.isPassword || scope.row.isAutoMode" type="success">开启</el-tag>
          <el-tag v-else type="info">关闭</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="凭证式模式" align="center" min-width="10%">
        <template #default="scope">
          <el-tag v-if="scope.row.isClient || scope.row.isAutoMode" type="success">开启</el-tag>
          <el-tag v-else type="info">关闭</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="身份令牌时效(秒)" prop="accessTokenTimeout" align="center" min-width="15%" />
      <el-table-column label="刷新令牌时效(秒)" prop="refreshTokenTimeout" align="center" min-width="15%" />

      <el-table-column label="操作" align="center" min-width="20%">
        <template #default="scope">
          <el-button
            type="primary"
            :icon="Search"
            circle
            plain
            @click.stop="handleInfo(scope.row)"
          />
          <el-button
            type="primary"
            :icon="Edit"
            circle
            plain
            @click.stop="handleUpdate(scope.row)"
          />
          <el-button
            type="danger"
            :icon="Delete"
            circle
            plain
            @click.stop="handleDelete(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页工具条 -->
    <pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.current"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />

    <!-- 表单弹窗 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px">
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="130px"
      >
        <el-row v-if="state.dialog.type=='info'">
          <el-col>
            <el-form-item label="ID" prop="id">
              <el-input v-model="formData.id" :disabled="state.dialog.read"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入名称" :disabled="state.dialog.read"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
          <el-form-item label="秘钥" prop="secret">
            <el-input v-model="formData.secret" type="textarea" placeholder="请输入秘钥" :disabled="state.dialog.read"/>
          </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="访问域" prop="scope">
              <el-input v-model="formData.scope" type="textarea" placeholder="请输入域(多个用逗号隔开)" :disabled="state.dialog.read"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="授权URL" prop="allowUrl">
              <el-input v-model="formData.allowUrl" type="textarea" placeholder="请输入授权的URL,多个用逗号隔开(可以使用 * 号通配符)" :disabled="state.dialog.read"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col >
            <el-form-item label="回调地址" prop="redirectUrl">
              <el-input v-model="formData.redirectUrl" placeholder="请输入回调地址" :disabled="state.dialog.read"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份令牌时效" prop="accessTokenTimeout">
              <el-input v-model="formData.accessTokenTimeout" placeholder="请输入认证令牌时效" :disabled="state.dialog.read"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="刷新令牌时效" prop="refreshTokenTimeout">
              <el-input v-model="formData.refreshTokenTimeout" placeholder="请输入刷新令牌时效" :disabled="state.dialog.read"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="全局开关" >
          <el-radio-group v-model="formData.isAutoMode" :disabled="state.dialog.read">
            <el-radio :label="true">开启</el-radio>
            <el-radio :label="false">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="授权码模式">
              <el-radio-group v-model="formData.isCode" :disabled="state.dialog.read">
                <el-radio :label="true">开启</el-radio>
                <el-radio :label="false">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.isCode">
            <el-form-item label="授权码时效" prop="codeTimeout">
              <el-input v-model="formData.codeTimeout" placeholder="请输入认证令牌时效" :disabled="state.dialog.read"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="密码式模式">
          <el-radio-group v-model="formData.isPassword" :disabled="state.dialog.read">
            <el-radio :label="true">开启</el-radio>
            <el-radio :label="false">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="凭证式模式">
          <el-radio-group v-model="formData.isClient" :disabled="state.dialog.read">
            <el-radio :label="true">开启</el-radio>
            <el-radio :label="false">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">

          <el-form v-if="state.dialog.type=='info'">
            <el-button @click="cancel"> 关闭 </el-button>
          </el-form>
          <el-form v-if="state.dialog.type!='info'">
            <el-button type="primary" @click="submitForm"> 确定 </el-button>
            <el-button @click="cancel"> 取消 </el-button>
          </el-form>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  listClientPages,
  getClientFormDetial,
  addClient,
  updateClient,
  deleteClients,
} from '@/api/system/client';
import { Search, Plus, Edit, Refresh, Delete } from '@element-plus/icons-vue';
import { onMounted, reactive, getCurrentInstance, ref, toRefs } from 'vue';
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import {
  ClientFormData,
  ClientItem,
  ClientQueryParam,
} from '@/types/api/system/client';
import { Option } from '@/types/common';

const { proxy }: any = getCurrentInstance();

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const state = reactive({
  loading: true,
  // 选中ID数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  queryParams: {
    current: 1,
    pageSize: 10,
  } as ClientQueryParam,
  clientList: [] as ClientItem[],
  total: 0,
  dialog: {
    title: '',
    visible: false,
    type: 'create',
    read: false,
  },
  formData: {} as ClientFormData,
  rules: {
    name: [
      { required: true, message: '客户端ID不能为空', trigger: 'blur' },
    ],
  },
});

const {
  loading,
  ids,
  multiple,
  queryParams,
  clientList,
  total,
  dialog,
  formData,
  rules,
} = toRefs(state);

function handleQuery() {
  listClientPages(state.queryParams).then(({ data }) => {
    state.clientList = data.list;
    state.total = data.total;
    state.loading = false;
  });
}

function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

function handleSelectionChange(selection: any) {
  state.ids = selection.map((item: any) => item.id);
  state.single = selection.length !== 1;
  state.multiple = !selection.length;
}

function handleAdd() {
  state.dialog = {
    title: '添加客户端',
    visible: true,
    type: 'create',
  };
}

function handleUpdate(row: any) {
  state.dialog = {
    title: '修改客户端',
    visible: true,
    type: 'edit',
  };
  getClientFormDetial(row.id).then(({ data }) => {
    state.formData = data;
  });
}

function handleInfo(row: any) {
  state.dialog = {
    title: '客户端详情',
    visible: true,
    type: 'info',
    read: true,
  };
  getClientFormDetial(row.id).then(({ data }) => {
    state.formData = data;
  });
}

function submitForm() {
  dataFormRef.value.validate((isvalid: boolean) => {
    if (isvalid) {
      if (state.dialog.type == 'edit') {
        updateClient(state.formData.id, state.formData).then(() => {
          ElMessage.success('修改成功');
          state.dialog.visible = false;
          cancel();
          handleQuery();
        });
      } else {
        addClient(state.formData).then(() => {
          ElMessage.success('新增成功');
          cancel();
          handleQuery();
        });
      }
    }
  });
}

function resetForm() {
  dataFormRef.value.resetFields();
  state.checkedAuthorizedGrantTypes = [];
}

function cancel() {
  resetForm();
  state.dialog.visible = false;
}

function handleDelete(row: any) {
  const clientIds = [row.id || state.ids].join(',');
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteClients(clientIds).then(() => {
        ElMessage.success('删除成功');
        handleQuery();
      });
    })
    .catch(() => ElMessage.info('已取消删除'));
}

onMounted(() => {
  handleQuery();
});
</script>

